<template>
  <view class="page-container">
    <!-- 固定头部区域 -->
    <view class="fixed-header" :style="{ paddingTop: statusBarHeight + 'px' }">
      <!-- 导航栏 -->
      <view class="nav-bar">
        <view class="title">设备管理</view>
        <view class="right-actions">
          <text @tap="openDeviceConfig" class="add-icon">+</text>
        </view>
      </view>
    </view>

    <!-- 可滚动内容区域 -->
    <scroll-view 
      class="scrollable-content"
      :style="{ top: `calc(${statusBarHeight}px + 88rpx)` }"
      scroll-y 
      refresher-enabled
      :refresher-triggered="refreshing"
      @refresherrefresh="refresh"
    >
      <!-- banner区域蓝牙配网 -->
      <view class="banner-box" @tap="openDeviceConfig">
        <image src="/static/GLOBAL.png" mode="aspectFill" class="banner-img" />
        <view class="banner-text">智能硬件配网</view>
        <view class="banner-btn">添加设备</view>
      </view>

      <!-- 设备列表 -->
      <view class="device-list">
        <view class="device-item" v-for="item in devList" :key="item.id">
          <view class="content">
            <view class="title">{{ item.nickname || item.name || '设备昵称' }}</view>
            <view class="status" :class="item.isOnline === 1 ? 'online' : 'offline'">
              {{ item.isOnline === 1 ? '在线' : '离线' }}
            </view>
            
            <view class="info-row">
              <!-- <text class="info-label">配置智能体:</text>
              <text class="info-value">{{ item.smartDeviceId ? '昵称XXX' : '未配置' }}</text> -->
            </view>
            <view class="info-row">
              <text class="info-label">设备SN:</text>
              <text class="info-value">{{ item.deviceSn || 'XXXXXXXXXXXXX' }}</text>
            </view>
            
            <view class="action-row">
              <view class="detail-btn" @tap="viewDeviceDetail(item)">设备详情</view>
              <view class="del-btn" @tap="deleteDevice(item)">删除设备</view>
            </view>
          </view>
        </view>
      </view>

      <!-- 空数据状态 -->
      <view class="empty-state" v-if="!devList.length">
        <text class="empty-text">暂无设备</text>
      </view>
    </scroll-view>

    <!-- 设备详情弹窗 -->
    <view v-if="showDetailDialog" class="custom-popup">
      <view class="popup-mask" @tap="showDetailDialog = false"></view>
      <view class="dialog-content detail-dialog">
        <view class="dialog-title">设备详情</view>
        <view class="device-detail-content">
          <view class="detail-item">
            <text class="label">设备名称:</text>
            <text class="value">{{ currentDevice.nickname || currentDevice.name || '未命名设备' }}</text>
          </view>
          <view class="detail-item">
            <text class="label">设备SN:</text>
            <text class="value">{{ currentDevice.deviceSn || '-' }}</text>
          </view>
          <view class="detail-item">
            <text class="label">MAC地址:</text>
            <text class="value">{{ currentDevice.macAddress || '-' }}</text>
          </view>
          <view class="detail-item">
            <text class="label">固件版本:</text>
            <text class="value">{{ currentDevice.firmwareVersion || '-' }}</text>
          </view>
          <view class="detail-item">
            <text class="label">IP地址:</text>
            <text class="value">{{ currentDevice.ipAddress || '-' }}</text>
          </view>
          <view class="detail-item">
            <text class="label">智能体ID:</text>
            <text class="value">{{ currentDevice.smartDeviceId || '未配置' }}</text>
          </view>
          <view class="detail-item">
            <text class="label">在线状态:</text>
            <text class="value status" :class="currentDevice.isOnline === 1 ? 'online' : 'offline'">
              {{ currentDevice.isOnline === 1 ? '在线' : '离线' }}
            </text>
          </view>
          <view class="detail-item">
            <text class="label">最后在线时间:</text>
            <text class="value">{{ formatDateTime(currentDevice.lastOnlineTime) }}</text>
          </view>
        </view>
        <view class="dialog-actions">
          <button @tap="editDevice(currentDevice)" class="edit-detail-btn">编辑设备</button>
          <button @tap="showDetailDialog = false" class="cancel-btn">关闭</button>
        </view>
      </view>
    </view>

    <!-- 添加/编辑设备弹窗 -->
    <view v-if="showDialog" class="custom-popup">
      <view class="popup-mask" @tap="showDialog = false"></view>
      <view class="dialog-content">
        <view class="dialog-title">{{ editIndex > -1 ? '编辑设备' : '添加设备' }}</view>
        <view class="form-item">
          <text class="form-label">设备名称</text>
          <input 
            v-model="form.nickname" 
            placeholder="请输入设备名称" 
            class="dialog-input"
          />
        </view>
        <view class="form-item" v-if="editIndex === -1">
          <text class="form-label">MAC地址</text>
          <input 
            v-model="form.macAddress" 
            placeholder="请输入MAC地址" 
            class="dialog-input"
          />
        </view>
        <view class="form-item" v-if="editIndex === -1">
          <text class="form-label">产品ID</text>
          <input 
            v-model="form.productId" 
            placeholder="请输入产品ID" 
            class="dialog-input"
          />
        </view>
        <view class="dialog-actions">
          <button @tap="saveDevice" class="confirm-btn">保存</button>
          <button @tap="showDialog = false" class="cancel-btn">取消</button>
        </view>
      </view>
    </view>

    <!-- 底部导航 -->
    <view class="fixed-footer">
      <TabBar :current-tab="2" />
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import NavBar from '@/components/NavBar/NavBar.vue'
import TabBar from '@/components/TabBar/TabBar.vue'
import system from '@/utils/system'
import { token } from '@/utils'
import { useDeviceStore, useHardwareStore, useUserStore } from '@/stores';
import request from '@/api/index'

const deviceStore = useDeviceStore();
const hardwareStore = useHardwareStore();
const userStore = useUserStore();
const statusBarHeight = system.getStatusBarHeight()

const devList = ref([])
const showDialog = ref(false)
const showDetailDialog = ref(false)
const refreshing = ref(false)
const form = ref({ 
  nickname: '', 
  macAddress: '', 
  productId: '',
  firmwareVersion: 'V1.0.0'
})
const currentDevice = ref({})
const editIndex = ref(-1)

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '-';
  try {
    const date = new Date(dateTimeStr);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
  } catch (e) {
    return dateTimeStr;
  }
}

// device-manage.vue 修复loadDevices函数
// 替换原有的loadDevices函数
const loadDevices = async () => {
  try {
    // 先检查本地缓存
    const cachedDevices = uni.getStorageSync('hardwareDevices');
    
    if (cachedDevices && !refreshing.value) {
      console.log('使用缓存的设备列表数据');
      devList.value = cachedDevices;
      return;
    }
    
    console.log('从服务器加载设备列表数据');
    // 检查是否为游客模式
    if (userStore.isGuestMode) {
      console.log('游客模式，加载演示设备')
      
      // 使用API中为游客模式准备的模拟数据
      // 直接使用index.js中已经实现的模拟数据返回逻辑
      try {
        // 直接请求硬件设备API，因为index.js中已经对'/hardware/user'路径做了游客模式的处理
        const res = await uni.request({
          url: request.getBaseUrl() + '/hardware/user',
          method: 'GET'
        });
        
        if (res.statusCode === 200 && res.data && res.data.code === 200) {
          devList.value = res.data.data || [];
          // 存储到缓存
          uni.setStorageSync('hardwareDevices', devList.value);
          console.log('游客模式成功加载模拟设备:', devList.value);
        } else {
          // 如果API调用不成功，提供一个默认的游客模式设备数据
          devList.value = [{
            id: 3001,
            deviceId: "HW12345",
            name: "智能助手设备",
            nickname: "智能助手设备",
            deviceSn: "SN123456789",
            macAddress: "AA:BB:CC:DD:EE:FF",
            status: "online",
            isOnline: 1,
            lastOnlineTime: new Date().toISOString(),
            firmwareVersion: "V1.0.0",
            ipAddress: "192.168.1.100"
          }];
          // 存储到缓存
          uni.setStorageSync('hardwareDevices', devList.value);
          console.log('使用默认游客设备数据:', devList.value);
        }
        return;
      } catch (error) {
        console.error('游客模式加载演示设备失败:', error);
        // 提供默认数据，确保列表不为空
        devList.value = [{
          id: 3001,
          deviceId: "HW12345",
          name: "智能助手设备",
          nickname: "智能助手设备",
          deviceSn: "SN123456789",
          macAddress: "AA:BB:CC:DD:EE:FF",
          status: "online",
          isOnline: 1,
          lastOnlineTime: new Date().toISOString(),
          firmwareVersion: "V1.0.0",
          ipAddress: "192.168.1.100"
        }];
        // 存储到缓存
        uni.setStorageSync('hardwareDevices', devList.value);
        console.log('使用默认游客设备数据:', devList.value);
        return;
      }
    }
    
    // 非游客模式逻辑保持不变
    // 非游客模式 - 获取当前用户ID和Token
    const userId = uni.getStorageSync('userId')
    const userToken = token.getToken()

    // 检查用户ID和Token是否存在
    if (!userId) {
      uni.showToast({ title: '未登录，请先登录', icon: 'none' })
      return
    }

    if (!userToken) {
      // 尝试刷新token
      const refreshResult = await userStore.refreshToken()
      if (!refreshResult) {
        uni.showToast({ title: 'Token已过期，请重新登录', icon: 'none' })
        return
      }
    }

    // 使用硬件模块API获取设备列表
    try {
      // 尝试使用hardware store的方法获取设备列表
      const devices = await hardwareStore.getDeviceRegistrations();
      if (devices && devices.length > 0) {
        devList.value = devices;
        // 存储到缓存
        uni.setStorageSync('hardwareDevices', devList.value);
        console.log('从hardware store获取到设备列表:', devList.value);
        return;
      }
    } catch (storeError) {
      console.warn('从hardware store获取设备列表失败，尝试直接API调用:', storeError);
    }

    // 如果使用store方法失败，直接调用API
    const res = await uni.request({
      url: 'https://gushu.szxhdkj.com/hardware/user',
      method: 'GET',
      data: { userId },
      header: {
        'Authorization': `Bearer ${userToken}`,
        'Content-Type': 'application/json'
      }
    })

    console.log('设备列表响应:', res)

    // 处理响应
    if (res.statusCode === 200 && res.data && res.data.code === 200) {
      // 成功获取设备列表
      devList.value = res.data.data || []
      // 存储到缓存
      uni.setStorageSync('hardwareDevices', devList.value);
      console.log('通过API直接获取到设备列表:', devList.value)
    } else {
      // 如果直接API调用也失败，尝试从device store获取
      try {
        await deviceStore.loadPrivateDevices()
        devList.value = deviceStore.privateDevices || []
        // 存储到缓存
        uni.setStorageSync('hardwareDevices', devList.value);
        console.log('从device store获取到设备列表:', devList.value)
      } catch (deviceStoreError) {
        console.error('从device store获取设备失败:', deviceStoreError)
        uni.showToast({ 
          title: res.data?.message || '获取设备列表失败', 
          icon: 'none' 
        })
      }
    }
  } catch (error) {
    console.error('加载设备列表发生错误:', error)
    uni.showToast({ 
      title: '网络异常，请检查网络连接', 
      icon: 'none' 
    })
  }
}

// 打开设备配置页面（蓝牙配网）
const openDeviceConfig = () => { 
  uni.navigateTo({ url: '/pages/BlueWifi/BlueWifi' }); 
};

// 查看设备详情
const viewDeviceDetail = (item) => {
  currentDevice.value = { ...item };
  showDetailDialog.value = true;
}

// 编辑设备
const editDevice = (item) => {
  form.value = { 
    ...item,
    nickname: item.nickname || item.name || ''
  };
  editIndex.value = devList.value.findIndex(d => d.id === item.id);
  showDialog.value = true;
  
  // 如果是设备详情页面打开的编辑，先关闭详情页面
  if (showDetailDialog.value) {
    showDetailDialog.value = false;
  }
}

// 保存设备
const saveDevice = async () => {
  if (!form.value.nickname) {
    uni.showToast({ title: '设备名称不能为空', icon: 'none' })
    return
  }

  try {
    let result;
    
    if (editIndex.value > -1) {
      // 使用hardware store更新设备
      const deviceId = devList.value[editIndex.value].id;
      result = await hardwareStore.updateHardwareDevice(deviceId, { 
        nickname: form.value.nickname,
        // 明确指定 isOnline 为数字
        isOnline: devList.value[editIndex.value].isOnline === true ? 1 : 0
      });
    } else {
      // 创建新设备
      const deviceData = {
        nickname: form.value.nickname,
        macAddress: form.value.macAddress,
        productId: form.value.productId,
        firmwareVersion: form.value.firmwareVersion || 'V1.0.0',
        userId: uni.getStorageSync('userId')
      };
      
      try {
        // 尝试注册设备
        result = await hardwareStore.registerDevice(deviceData);
      } catch (registerError) {
        console.error('注册设备失败，尝试直接创建:', registerError);
        // 如果注册失败，尝试直接创建
        result = await hardwareStore.createHardwareDevice(deviceData);
      }
    }
    
    if (result) {
      uni.showToast({ 
        title: editIndex.value > -1 ? '更新成功' : '添加成功', 
        icon: 'success' 
      });
      
      // 重新加载设备列表
      await loadDevices();
      showDialog.value = false;
    } else {
      throw new Error(editIndex.value > -1 ? '更新设备失败' : '添加设备失败');
    }
  } catch (error) {
      console.error('保存设备失败:', error);
      uni.showToast({ 
        title: error.message || '操作失败', 
        icon: 'none' 
      });
    }
  }

// 删除设备
const deleteDevice = (item) => {
  uni.showModal({
    title: '确认删除',
    content: `确定删除设备 ${item.nickname || item.name || '未命名设备'} 吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          // 尝试使用hardware store删除设备
          const result = await hardwareStore.deleteDevice(item.id);
          
          if (result) {
            uni.showToast({ 
              title: '删除成功', 
              icon: 'success' 
            });
            // 删除成功后刷新列表
            await loadDevices();
          } else {
            // 如果store方法失败，尝试直接API调用
            const userToken = uni.getStorageSync('token');
            if (!userToken) {
              uni.showToast({ title: 'Token已过期，请重新登录', icon: 'none' });
              return;
            }
          
            const deleteRes = await uni.request({
              url: `https://gushu.szxhdkj.com/hardware/device/${item.id}`,
              method: 'DELETE',
              header: {
                'Authorization': `Bearer ${userToken}`,
                'Content-Type': 'application/json'
              }
            });
          
            if (deleteRes.statusCode === 200 && deleteRes.data.code === 200) {
              uni.showToast({ 
                title: '删除成功', 
                icon: 'success' 
              });
              // 删除成功后刷新列表
              await loadDevices();
            } else {
              throw new Error(deleteRes.data.message || '删除设备失败');
            }
          }
        } catch (error) {
          console.error('删除设备失败:', error);
          uni.showToast({ 
            title: error.message || '删除失败', 
            icon: 'none' 
          });
        }
      }
    }
  });
}

// 刷新设备列表
const refresh = async () => {
  refreshing.value = true;
  await loadDevices();
  setTimeout(() => {
    refreshing.value = false;
  }, 800);
}

// 设置路由变化监听
const setupRouteWatcher = () => {
  // 获取当前页面路由对象
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  
  if (currentPage) {
    // 手动监听页面显示事件
    const onShowHandler = () => {
      console.log('device-manage页面显示，刷新数据');
      // 如果设备列表为空或从蓝牙配网页面返回，刷新设备列表
      if (devList.value.length === 0 || pages.length > 1 && pages[pages.length - 2].route && 
         pages[pages.length - 2].route.includes('BlueWifi')) {
        loadDevices();
      }
    };
    
    // 添加页面显示事件监听
    currentPage.onShow = function() {
      onShowHandler();
      // 保留原有的onShow逻辑，如果有的话
      if (this.$mp && this.$mp.page && this.$mp.page._onShow) {
        this.$mp.page._onShow();
      }
    };
  }
};

// 监听登录状态变化事件
const setupLoginListener = () => {
  uni.$on('loginStateChanged', (data) => {
    console.log('设备管理页面检测到登录状态变化，强制刷新数据');
    // 登录成功后清除缓存，确保获取最新数据
    uni.removeStorageSync('hardwareDevices');
    // 设置为刷新状态，强制从服务器获取数据
    refreshing.value = true;
    // 确保userId已更新
    setTimeout(() => {
      loadDevices().finally(() => {
        refreshing.value = false;
      });
    }, 500) // 延迟执行，确保userId已经被设置
  })
}

// 组件加载时获取设备列表
onMounted(() => {
  // 设置路由变化监听
  setupRouteWatcher();
  
  loadDevices();
  setupLoginListener();
})

// 组件卸载时移除事件监听
onUnmounted(() => {
  uni.$off('loginStateChanged');
})
</script>

<style lang="scss" scoped>
.page-container {
  width: 100vw;
  height: 100vh;
  position: fixed;
  left: 0;
  top: 0;
  background: #f8f9fa;

  .fixed-header {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 100;
    background: #fff;

    .nav-bar {
      height: 88rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 30rpx;
      border-bottom: 1px solid #f5f5f5;

      .title {
        font-size: 36rpx;
        font-weight: 600;
        color: #333;
      }

      .right-actions {
        .add-icon {
          font-size: 48rpx;
          color: #5677fc;
        }
      }
    }
  }

  .scrollable-content {
    position: fixed;
    left: 0;
    right: 0;
    bottom: calc(110rpx + env(safe-area-inset-bottom));
    background: #f8f9fa;
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;
    padding-bottom: 20rpx;
    padding-top: 30rpx;

    .banner-box {
      margin: 24rpx 30rpx;
      border-radius: 20rpx;
      overflow: hidden;
      position: relative;
      background: linear-gradient(135deg, #5677fc, #38a0ff);
      height: 200rpx;
      
      .banner-img {
        position: absolute;
        right: 30rpx;
        top: 50%;
        transform: translateY(-50%);
        width: 100rpx;
        height: 100rpx;
        opacity: 0.9;
      }
    
      .banner-text {
        position: absolute;
        left: 30rpx;
        top: 50rpx;
        font-size: 36rpx;
        font-weight: bold;
        color: #fff;
        text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.2);
      }
    
      .banner-btn {
        position: absolute;
        left: 30rpx;
        bottom: 40rpx;
        background: rgba(255, 255, 255, 0.9);
        color: #5677fc;
        padding: 12rpx 32rpx;
        border-radius: 32rpx;
        font-size: 26rpx;
        font-weight: 500;
        box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
      }
    }

    .device-list {
      padding: 0 30rpx;

      .device-item {
        background: #ffffff;
        border-radius: 16rpx;
        margin-bottom: 24rpx;
        overflow: hidden;
        box-shadow: 0 4rpx 16rpx rgba(86, 119, 252, 0.1);
        border: 1px solid #f0f3ff;
        
        .content {
          padding: 24rpx 30rpx;
          position: relative;
          
          .title {
            font-size: 32rpx;
            font-weight: 600;
            color: #333;
            margin-bottom: 16rpx;
            padding-right: 120rpx;
          }
          
          .status {
            position: absolute;
            top: 24rpx;
            right: 30rpx;
            font-size: 24rpx;
            border-radius: 30rpx;
            padding: 4rpx 16rpx;
            
            &.online {
              background-color: rgba(86, 119, 252, 0.1);
              color: #5677fc;
            }
            
            &.offline {
              background-color: #f5f5f5;
              color: #999;
            }
          }
          
          .info-row {
            font-size: 26rpx;
            color: #666;
            margin-bottom: 14rpx;
            display: flex;
            
            .info-label {
              color: #999;
              margin-right: 10rpx;
            }
            
            .info-value {
              color: #333;
              flex: 1;
            }
          }
          
          .action-row {
            display: flex;
            justify-content: flex-end;
            margin-top: 20rpx;
            border-top: 1px solid #f0f3ff;
            padding-top: 16rpx;
            
            .detail-btn, .del-btn {
              padding: 8rpx 20rpx;
              font-size: 24rpx;
              text-align: center;
              border-radius: 6rpx;
              margin-left: 16rpx;
            }
            
            .detail-btn {
              background-color: #5677fc;
              color: #fff;
            }
            
            .del-btn {
              background-color: #fff;
              color: #f56c6c;
              border: 1px solid #f56c6c;
            }
          }
        }
      }
    }

    .empty-state {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding-top: 100rpx;

      .empty-img {
        width: 300rpx;
        height: 210rpx;
        margin-bottom: 30rpx;
      }

      .empty-text {
        font-size: 32rpx;
        color: #999;
        margin-bottom: 30rpx;
      }

      .add-device-btn {
        display: flex;
        align-items: center;
        background: #5677fc;
        color: #fff;
        padding: 16rpx 32rpx;
        border-radius: 32rpx;

        .add-icon {
          font-size: 36rpx;
          margin-right: 8rpx;
        }
      }
    }
  }

  .custom-popup {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 999;
    display: flex;
    justify-content: center;
    align-items: center;

    .popup-mask {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, 0.4);
    }

    .dialog-content {
      position: relative;
      background: #fff;
      border-radius: 16rpx;
      width: 80%;
      padding: 40rpx;
      z-index: 1000;

      &.detail-dialog {
        max-height: 80vh;
        overflow-y: auto;
      }

      .dialog-title {
        font-size: 36rpx;
        font-weight: 600;
        color: #333;
        text-align: center;
        margin-bottom: 30rpx;
      }

      .form-item {
        margin-bottom: 20rpx;
        
        .form-label {
          display: block;
          font-size: 28rpx;
          color: #333;
          margin-bottom: 10rpx;
        }
      }

      .dialog-input {
        border: 1px solid #eee;
        border-radius: 8rpx;
        margin-bottom: 16rpx;
        padding: 16rpx;
        width: 100%;
        box-sizing: border-box;
      }
      
      .device-detail-content {
        .detail-item {
          display: flex;
          margin-bottom: 20rpx;
          
          .label {
            width: 180rpx;
            font-size: 28rpx;
            color: #666;
            flex-shrink: 0;
          }
          
          .value {
            flex: 1;
            font-size: 28rpx;
            color: #333;
            word-break: break-all;
            
            &.status {
              &.online {
                color: #67c23a;
              }
              
              &.offline {
                color: #909399;
              }
            }
          }
        }
      }

      .dialog-actions {
        display: flex;
        justify-content: space-between;
        margin-top: 30rpx;

        button {
          flex: 1;
          margin: 0 8rpx;
          height: 80rpx;
          line-height: 80rpx;
          border-radius: 16rpx;
          font-size: 28rpx;
        }

        .confirm-btn, .edit-detail-btn {
          background: #5677fc;
          color: #fff;
        }

        .cancel-btn {
          background: #f5f5f5;
          color: #666;
        }
      }
    }
  }

  .fixed-footer {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 100;
    background: #fff;
    padding-bottom: env(safe-area-inset-bottom);
    border-top: 1px solid #f5f5f5;
  }
}
</style>